package com.vincent.realm;


import com.vincent.common.utils.ResultMapUtil;
import com.vincent.service.RealmService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 用户登录验证授权
 */
public class AdminRealm extends AuthorizingRealm {
    @Resource
    private RealmService realmService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        int userId = Integer.parseInt(principals.getPrimaryPrincipal().toString());
        Map<String, Object> serviceMap = realmService.findAdminAuthorizationInfo(userId);
        Object successObj = ResultMapUtil.getSuccessObj(serviceMap);
        SimpleAuthorizationInfo authorizationInfo = (SimpleAuthorizationInfo) successObj;
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        String password = new String((char[]) token.getCredentials());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username,
                password,
                getName()
        );
        return authenticationInfo;
    }
}
